<template>
    <div :class='{"imageViewItem2":true,"imageViewItem2_1":isWidths=="Y" ? true:false}'>
        <div class='titles'>
            {{label}}
        </div>
         <el-carousel :style="{'height':imgHeight}" @change="changeImg" v-if="!isShowAll" class="imgitem">
            <el-carousel-item  v-for="(image,index) in imageList" :key="index">
                 <el-image
                   
                    :src="image.url"
                    fit="fill" 
                    :preview-src-list="srcList"  ></el-image>
            </el-carousel-item>
        </el-carousel>
        <div style='width:100%;text-align:center'  v-if="!isShowAll">
            <i class='el-icon-upload' @click="uploads('')" v-if="isreadonly!='Y'&&isShowSc" title="上传" style='margin:10px;font-size:28px;cursor:pointer'></i>
            <i class='el-icon-camera-solid' @click="mainDevs" v-if="isreadonly!='Y'" title="高拍仪主摄像头上传"  style='margin:10px;font-size:28px;cursor:pointer'></i>
            <i class='fa fa-cloud-download' @click="downImg('-1')" v-if="isDownLoad!='N'" title="下载"  style='margin:10px;font-size:28px;cursor:pointer'></i>
            <i class='fa fa-times' @click="delImg('')" v-if="isreadonly!='Y'" title="删除"  style='margin:10px;font-size:28px;cursor:pointer'></i>
            <i class='fa fa-print' @click="prints('')" v-if="isreadonly!='Y'" title="打印"  style='margin:10px;font-size:28px;cursor:pointer'></i>
            <i class='el-icon-camera' @click="childDevs" v-if="isreadonly!='Y'" title="高拍仪副摄像头上传" style='margin:10px;font-size:28px;cursor:pointer;display:none'></i>
         
        </div>
         <div style='width:100%;text-align:center'  v-if="isShowAll">
              <i class='el-icon-camera-solid' @click="mainDevs" v-if="isreadonly!='Y'" title="高拍仪主摄像头上传"  style='margin:10px;font-size:28px;cursor:pointer'><span style='font-size:14px'>高拍仪上传</span></i>
            <i class='el-icon-upload' @click="uploads(item)" v-if="isreadonly!='Y'&&isShowUpload&&isShowSc" :title="item" style='margin:10px;font-size:28px;cursor:pointer' v-for="(item,index) in names2" :key="index"><span style='font-size:14px'>{{item}}</span></i>
          
            <i class='el-icon-camera' @click="childDevs" v-if="isreadonly!='Y'" title="高拍仪副摄像头上传" style='margin:10px;font-size:28px;cursor:pointer;display:none'></i>
         
        </div>
        <div  v-if="isShowAll" style='min-height:200px;min-width:900px'>
                <div  v-for="(image,index) in imageList" :key="index" class='image_item'>
                 <el-image
                    
                    :src="image.url"
                    fit="contain" 
                    :preview-src-list="srcList"  ></el-image>
                    <div style='width:100%;text-align:center'>
                        {{image.name}}
                        <i class='fa fa-cloud-download' @click="downImg(index)"  v-if="isDownLoad!='N'" title="下载"  style='margin:10px;font-size:22px;cursor:pointer'></i>
                        <i class='fa fa-print' @click="prints(index)" v-if="isreadonly!='Y'" title="打印"  style='margin:10px;font-size:28px;cursor:pointer'></i>
           
                        <i class='fa fa-times' @click="delImg(index)" v-if="isreadonly!='Y'" title="删除"  style='margin:10px;font-size:22px;cursor:pointer'></i>
            
                    </div>
                </div>
        </div>
        <el-dialog
            title="上传"
            :visible.sync="dialogVisible"
            append-to-body
            width="80%">
            <el-upload
                class="upload-demo"
                drag
                :data="insertProgram"
                :before-upload="beforeAvatarUpload"
                accept="image/*,video/*"
                :action="action"
                :on-success="uploadSuccess"
                multiple>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>

         <el-dialog
            width="90%"
            title="打印预览"
            :visible.sync="printShow"
            append-to-body>
             <common-print :printDatas="printData" style='height:85VH' @closes="printShow=false"></common-print>
       
        </el-dialog>
    </div>
</template>
<script>
import HighShotImg from '../highShot/HighShotImg.vue'
import CommonPrint  from '../../views/common/print/CommonPrint.vue'
export default {
    name:'imageViewItemChild',
    props:['images','heights','id','data','index','isreadonly',"appid","label","exkey","isWidths","imageHeight"],
    components:{
        HighShotImg,
        CommonPrint
    },
    data(){
        return{
            srcList:[],
            dialogVisible:false,
            dialogVisible2:false,
            showType:"main",
            action:'',
            imageList:this.images,
            currentValue:'',
            styles:"",
            p:"",
            id_:"",
            curIndex:0,
            isShowSc:true,
            insertProgram: {
                model: "",
                type:"",
                id:"",
                name:"",
                keyPId:"",
                token:sessionStorage.getItem("token")
            },
            imgHeight:"300px",
            name_:"",
            action:"",
            isNewFile:false,
            imageMap:{},
            imageMap2:{},
            keyId:"",
            keyPId:"",
            isShowAll:false,
            isShowUpload:true,
            names:"",
            names2:[],
            fileKeyIndex:-1,
            isClose:"N",
            printData:{},
            printShow:false,
            mainUrl:"",
            isDownLoad:"Y",
            isCJ:"Y"//是否裁剪
        }
    },
    created(){
        console.log(this.exkey,"this.exkey=sss===")
        this.srcList=[];
       // alert(this.isreadonly)
        if(this.images){
            for(let i=0;i<this.images.length;i++){
                this.srcList.push(this.images[i].url)
            }
        }
        try{
            if(this.exkey.mainUrl){
                this.mainUrl=this.exkey.mainUrl;
            }
        }catch(e){}
        try{
            if(this.exkey.isDownLoad){
                this.isDownLoad=this.exkey.isDownLoad;
            }
        }catch(e){}
        try{
            if(this.exkey.imgHeight){
                this.imgHeight=this.exkey.imgHeight;
            }
            if(this.imageHeight){
                this.imgHeight=this.imageHeight;
            }
        }catch(e){}
        try{
            if(this.exkey.isCJ){
                this.isCJ=this.exkey.isCJ;
            }
        }catch(e){}
        try{
            this.insertProgram.model=this.exkey.model;
            this.insertProgram.type=this.exkey.type;
            
            let ids=this.exkey.id.split(".");
            this.insertProgram.id=this.data[ids[0]][ids[1]];
            
            this.keyId=ids[1];
            this.keyPId=ids[0];
            this.insertProgram.keyPId=ids[0]
           // alert(this.exkey.id)
            if(!this.insertProgram.id){
                this.insertProgram.id=this.randomString(12);
            }
            //alert(this.exkey.name+"=="+this.exkey.isShowAll)
            if(this.exkey.name){
              
                this.insertProgram.name=this.exkey.name;
                this.names=this.exkey.name;
                this.names2=this.exkey.name.split(",");
                if(this.exkey.names){
                    this.names2=this.exkey.names.split(",");
                }
                if(this.exkey.name.split(",").length==1){
                    this.name_=this.names2[0];
                }else{
                    this.name_=this.exkey.name;
                }
            }
           
            this.isNewFile=true;
            if(this.exkey.isShowAll){
                this.isShowAll=this.exkey.isShowAll=="Y" ? true:false;
            }
            
            if(this.exkey.isShowUpload){
                this.isShowUpload=this.exkey.isShowUpload=="Y" ? true:false;
            }
            if(this.exkey.isClose){
                this.isClose=this.exkey.isClose;
            }
        }catch(e){
            this.insertProgram.model="";
            this.insertProgram.type="";
            this.insertProgram.id="";
            this.insertProgram.name="";
            this.isClose="N";
        }
        this.action="/business/api/file/fileUpload";
       
        this.setData();
        this.loadPermission();
        let height=this.$parent.$parent.$parent.$parent.$parent.$el.clientHeight;
        let width=this.$parent.$parent.$parent.$parent.$parent.$el.clientWidth;
        this.styles="height:"+(height-200)+"px;width:"+width+"px;";
        window.setInterval(()=>{
            
            let reloadImg=sessionStorage.getItem("reloadImg")
            let imgField=sessionStorage.getItem("reloadImgField");
            if(reloadImg=="Y"){
                let isOk=true;
                if(imgField){
                    isOk=false;
                }
                if((","+imgField+",").indexOf(","+this.id+",")!=-1){
                    isOk=true;
                    imgField=imgField.replace(","+this.id+",","")
                    imgField=imgField.replace(","+this.id,"")
                    imgField=imgField.replace(this.id+",","")
                    imgField=imgField.replace(this.id,"")
                    sessionStorage.setItem("reloadImgField",imgField);
                }
                if(isOk){
                    try{
                        let ids=this.exkey.id.split(".");
                    // alert(this.data[ids[0]][ids[1]])
                        this.insertProgram.id=this.data[ids[0]][ids[1]];
                    }catch(e){}
                    if(!imgField)
                        sessionStorage.setItem("reloadImg","");
                    this.setData()
                }
                
            }
        },5000)
    },
    methods:{
        print(name,path,isPrint){
            let printData_={};
            printData_.printName=name;
            printData_.urlPath=path;
            printData_.sCurItem="";
            printData_.appid="business";
            printData_.token=sessionStorage.getItem("token");
            printData_.isPrint=isPrint;
            printData_.isSearch="Y"
            if(isPrint=="Y"){
                this.isPrint="Y";
            }else if(isPrint=="A"){
                this.isPrint="A";
            }else{
                this.isPrint="N";
                this.printShow=true;
                    //this.$emit("openWin",JSON.stringify(items))
            }
            printData_.isLodop=this.exkey.isLodop;
            printData_.printType=this.exkey.printType;
            printData_.printLeft=this.exkey.printLeft;
            printData_.printTop=this.exkey.printTop;
            this.printData=printData_;


        },
        loadPermission(){
            this.$post("api","/api/permission/getUserPermissionDetail",{perName:"图片上传"}).then(data=>{
                 if(data["图片上传"]){
                     //this.isShowSc=data["图片上传"]=="是" ? true:false;
                 }
            })
        },
        randomString(len) {
            len = len || 32;
            var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
            var maxPos = $chars.length;
            var pwd = '';
            for (let i = 0; i < len; i++) {
                pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
            }
            return pwd;
        },
        changeImg(index){
           this.curIndex=index;
        },
        closes(){
            this.dialogVisible2=false;
        },
        mainDevs(){
            //this.dialogVisible2=true;
           // this.showType="main";
            let data={};
            data.id=this.id;
            data.model=this.insertProgram.model;
            data.type=this.insertProgram.type;
            data.keyId=this.insertProgram.id;
            data.keyPId=this.insertProgram.keyPId;
            data.token=this.insertProgram.token;
            data.name=this.insertProgram.name;
            data.names=this.names;
            data.isClose=this.isClose;
            data.isCJ=this.isCJ
           this.$emit("mainDevs",JSON.stringify(data))
        },  
        childDevs(){
            //this.dialogVisible2=true;
           // this.showType="child";
            let data={};
            data.id=this.id;
            data.model=this.insertProgram.model;
            data.type=this.insertProgram.type;
            data.keyId=this.insertProgram.id;
            data.keyPId=this.insertProgram.keyPId;
            data.token=this.insertProgram.token;
            data.name=this.insertProgram.name;
            data.names=this.names;
           this.$emit("childDevs",JSON.stringify(data))
        },
        uploads(name){
            this.dialogVisible=true;
            if(name){
                this.insertProgram.name=name;
            }
        },

        prints(index){
            if((!index&&index!=0)||index==''){
                index=this.curIndex;
            }
            let url=this.imageList[index].url;
            url=this.mainUrl+url;
            this.print(this.label,url,"N")
        },
        delImg(index){
            if((!index&&index!=0)||index==''){
                index=this.curIndex;
            }
            this.$confirm('确定要删除这条图片, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let url=this.imageList[index].url;
                let ids=this.imageMap[url];
                this.imageList.splice(index,1);
                this.srcList.splice(index,1);
                this.currentValue="";
                
                
                for(let i=0;i<this.srcList.length;i++){
                    
                    this.currentValue=this.currentValue=="" ? this.srcList[i]:this.currentValue+","+this.srcList[i];
                }
                try{
                    if(this.srcList.length==0){
                        
                        this.data["fileKeys"][this.fileKeyIndex]["hasData"]="N";
                    }
                }catch(e){}
                

                /*let data={};
                data.id=this.id;
                data.val=this.currentValue;
                data.index=this.curIndex;*/
                 if(this.isNewFile){
                    let datas=this.data["imageList_"];
                    if(!datas){
                        datas=[];
                    }
                    let index=-1;
                    for(let i=0;i<datas.length;i++){
                        let data_=datas[i];
                        if(data_.model==this.insertProgram.model&&data_.type==this.insertProgram.type){
                            index=i;
                        }
                    }
                    
                    if(index==-1){
                        index=datas.length;
                        let data_={};
                        data_.model=this.insertProgram.model;
                        data_.type=this.insertProgram.type;
                        data_.sId=this.insertProgram.id;
                        data_.del_id=ids;
                        data_.id="";
                        data_.key=this.keyId;
                        data_.keyPid=this.keyPId;
                        datas.push(data_);
                        this.$set(this.data,"imageList_",datas)
                    }else{
                        let data_=datas[index];
                        let id=data_["del_id"];
                        id=id=="" ? ids:id+","+ids;
                        datas[index].del_id=id;
                        this.$set(this.data,"imageList_",datas)
                    }
                    
                }else{
                    if(this.p){
                        this.$set(this.data[this.p],this.id_,this.currentValue);
                    }else{
                        this.$set(this.data,this.id_,this.currentValue);
                    }
                }
                
            }).catch(() => {
             
            });
            
        },
        downImg(index){
            if((!index&&index!=0)||index=="-1"){
                index=this.curIndex;
            }
            let url=this.srcList[index];
            let a = document.createElement("a");
            a.href ='business/api/file/downFile?path='+url.replace("/business/image/","")+"&token="+sessionStorage.getItem("token");
            document.body.appendChild(a);
            a.click();  //下载
            URL.revokeObjectURL(a.href);    // 释放URL 对象 
            document.body.removeChild(a);   // 删除 a 标签

        },
        uploadImg(data){
            this.uploaded(JSON.parse(data));
        },
        uploadSuccess(response, file, fileList){
            this.uploaded(response);
            
            /*
            this.$emit('input',JSON.stringify(data));
            this.$emit('on-change',JSON.stringify(data));*/
            
        },
        uploaded(response){
            
             if(!this.imageList){
                this.imageList=[]; 
            }
            let ids="";
            for(let i=0;i<response.length;i++){
                this.imageList.push(response[i]);
                this.srcList.push(response[i].url)

                this.currentValue=this.currentValue=="" ? response[i].url:this.currentValue+","+response[i].url;
                ids=ids=="" ? response[i].f_id:ids+","+f_id;
                this.imageMap[response[i].url]=response[i].f_id
                this.imageMap2[response[i].url]=response[i].name
            }
           // console.log(this.data["fileKeys"],"fileKeys=========================");
           // console.log(this.fileKeyIndex)
             try{
                    this.data["fileKeys"][this.fileKeyIndex]["hasData"]="Y";
                }catch(e){}
           
            if(this.isNewFile){
                let datas=this.data["imageList_"];
                if(!datas){
                    datas=[];
                }
                let index=-1;
                for(let i=0;i<datas.length;i++){
                    let data_=datas[i];
                    if(data_.model==this.insertProgram.model&&data_.type==this.insertProgram.type){
                        index=i;
                    }
                }
                
                if(index==-1){
                    index=datas.length;
                    let data_={};
                    data_.model=this.insertProgram.model;
                    data_.type=this.insertProgram.type;
                    data_.id=ids;
                    data_.sId=this.insertProgram.id;
                    data_.key=this.keyId;
                    data_.keyPid=this.keyPId;
                    data_.del_id="";
                    datas.push(data_);
                    this.$set(this.data,"imageList_",datas)
                }else{
                    let data_=datas[index];
                    let id=data_["id"];
                    id=id=="" ? ids:id+","+ids;
                    datas[index].id=id;
                    this.$set(this.data,"imageList_",datas)
                }
                
            }else{
                 let data={};
                data.id=this.id;
                data.val=this.currentValue;
                data.index=this.index;
                if(this.p){
                    this.$set(this.data[this.p],this.id_,this.currentValue);
                }else{
                    this.$set(this.data,this.id_,this.currentValue);
                }
            }
            if(this.isClose=="Y"){
                this.dialogVisible=false;
            }
            this.$message({
                message: '上传成功!',
                type: 'success'
            });
            //console.log(this.data["imageList_"],"imageList_=========================")
        },
        beforeAvatarUpload(file) {
            let _this = this
            return new Promise((resolve, reject) => {
                
                let  isJPG = file.type.indexOf("image")!=-1||file.type.indexOf("video")!=-1;
               
                let isLt2M = file.size / 1024 / 1024 < 13 // 判定图片大小是否小于10MB
                let isLt2M2 = file.size / 1024 / 1024 > 3 // 判定图片大小是否小于10MB
                
                if(!isLt2M||!isJPG) {
                    reject()
                }
                if(file.type.indexOf("image")!=-1){
                    let image = new Image(), resultBlob = '';
                    image.src = URL.createObjectURL(file);
                    image.onload = () => {
                        if(isLt2M2){
                            // 调用方法获取blob格式，方法写在下边
                            resultBlob = _this.compressUpload(image, file);
                            resolve(resultBlob)
                        }else{
                            resolve(file);
                        }
                        
                    }
                    image.onerror = () => {
                        reject()
                    }
                }else{
                    
                    resolve(file);
                }
                
            })
            /*
            const isJPG = file.type.indexOf("image")!=-1;
            const isLt2M = file.size / 1024 / 1024 < 10;

            if (!isJPG) {
                this.$message.error('只能上传图片!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 10MB!');
            }
            return isJPG && isLt2M;*/
        },
                
        /* 图片压缩方法-canvas压缩 */
        compressUpload(image, file) {
            let canvas = document.createElement('canvas')
            let ctx = canvas.getContext('2d')
            let initSize = image.src.length
            let { width } = image, { height } = image
            canvas. width = width
            canvas.height = height
            ctx.fillRect(0, 0, canvas.width, canvas.height)
            ctx.drawImage(image, 0, 0, width, height)
            
            // 进行最小压缩0.1
            let compressData = canvas.toDataURL(file.type || 'image/jpeg', 0.5)
            
            // 压缩后调用方法进行base64转Blob，方法写在下边
            let blobImg = this.dataURItoBlob(compressData)
            return blobImg
        },
        
        /* base64转Blob对象 */
        dataURItoBlob(data) {
            let byteString;
            if(data.split(',')[0].indexOf('base64') >= 0) {
                byteString = atob(data.split(',')[1])
            }else {
                byteString = unescape(data.split(',')[1])
            }
            let mimeString = data
                .split(',')[0]
                .split(':')[1]
                .split(';')[0];
            let ia = new Uint8Array(byteString.length)
            for( let i = 0; i < byteString.length; i += 1) {
                ia[i] = byteString.charCodeAt(i)
            }
            return new Blob([ia], {type: mimeString})
        },
        setData(isOks){
            console.log("imgSetData=======================================")
            if((!this.images&&this.isNewFile)||isOks){
                let params=JSON.parse(JSON.stringify(this.insertProgram));
               // this.name_="";
                console.log(this.exkey,"setData===============")
                //alert(this.exkey.getAll)
               try{
                if(this.exkey.getAll&&this.exkey.getAll!='Y')
                    params.name=this.name_;
                else if(this.exkey.getAll&&this.exkey.getAll=='Y')
                    params.name="";
               }catch(e){
                    params.name=this.name_;
               }
                
               
                this.$post("business","/api/file/getFile",params).then(data=>{
                    
                    this.imageList=[];
                    this.srcList=[];
                    let isOk=false;
                    for(let i=0;i<data.length;i++){
                        if(data[i].url){
                            let data_={};
                            data_.url=data[i].url;
                            data_.name=data[i].name;
                            this.imageList.push(data_);
                            this.srcList.push(data[i].url);
                            this.imageMap[data[i].url]=data[i].id;
                            this.imageMap2[data[i].url]=data[i].name;
                            isOk=true;
                            
                        }
                        
                    }
                    //alert(this.imageList.length)
                   // console.log(params,"params=================================")
                    for(let i=0;i<this.data["fileKeys"].length;i++){
                        if(this.insertProgram.model==this.data["fileKeys"][i].model&&this.insertProgram.name==this.data["fileKeys"][i].name&&this.insertProgram.type==this.data["fileKeys"][i].type){
                            this.fileKeyIndex=i;
                        }
                    }
                    if(isOk){
                        
                        
                        if(this.fileKeyIndex>=0){
                            this.data["fileKeys"][this.fileKeyIndex]["hasData"]="Y";
                        }
                        
                    }else{
                        if(this.fileKeyIndex>=0){
                            this.data["fileKeys"][this.fileKeyIndex]["hasData"]="N";
                        }
                    }
                })
            }else if(!this.images){
                if(this.data){
                    let ids=this.id.split(".");
                    console.log("ids============"+this.id)
                    if(ids.length>1){
                        this.p=ids[0];
                        this.id_=ids[1];
                        if(this.index||this.index=='0'){
                            try{
                                this.currentValue=this.data[this.p][this.index][this.id_];
                            }catch(e){}
                        }else{
                            try{
                                this.currentValue=this.data[this.p][this.id_];
                            }catch(e){}
                        }
                        console.log("currentValue============"+this.currentValue)
                        let images=this.currentValue.split(",");
                        this.imageList=[];
                        this.srcList=[];
                        for(let i=0;i<images.length;i++){
                            if(images[i]){
                                let data={};
                                data.url=images[i];
                                this.imageList.push(data);
                                this.srcList.push(images[i]);
                            }
                            
                        }
                    }
                
                }
            }
        }
    }
}
</script>
<style scoped>
    .el-image{
        height:100%;
        margin-left:0;
        text-align:center;
    }
    .el-carousel__item{
        text-align:center;
    }
    .imgitem>>>.el-carousel__container{
        height:100%;
    }
</style>

<style>
.imageViewItem2{
    border:1px solid #ddd;
    margin:10px;
    box-sizing: border-box;
    overflow:hidden;
   
}
.imageViewItem2_1{
    border:1px solid #ddd;
    margin:10px;
    box-sizing: border-box;
    width:100%;
   
}
.upload-demo{
    width:100%;
    text-align:center;
}
.el-upload-list{
    height:50px;
    overflow: auto;
}
.img_item{
    padding:10px;
    border:1px solid #ddd;
    height:120px;
    width:120px;
    display:inline-block;
    border-radius: 5px;;
    margin-left:10px;
}
.titles{
    text-align:center;
    padding:5px;
    border-bottom:1px solid #ddd;
    background:#e1e9f1;
}
.image_item{
    width:200px;
    display:inline-block;
    margin:10px;
}
</style>